package exam.daoImpl;

import demo03.hw4_25;
import exam.dao.UserDao;
import exam.pojo.User;
import exam.tool.ConnectionTool;
import exam.tool.Const;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class UserDaoImpl implements UserDao {

    Connection conn = null;

    static {
        try {
            Class.forName(Const.DRIVER);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean insert(List<User> people) {

        PreparedStatement ps_insert = null;
        boolean result = true;

        try {
            conn = ConnectionTool.getDefaultConn();

            conn.setAutoCommit(false);

            String sql = "insert into people values(?,?,?,?,?)";

            ps_insert = conn.prepareStatement(sql);

            for (User person : people) {
                ps_insert.setInt(1, person.getUserno());
                ps_insert.setString(2, person.getUserName());
                ps_insert.setString(3, person.getPassword());
                ps_insert.setString(4, person.getJob());
                ps_insert.setInt(5, person.getSal());
                ps_insert.addBatch();
            }

            int[] insertCount = ps_insert.executeBatch();
            if (insertCount.length == people.size() && Arrays.stream(insertCount).allMatch(num -> num == 1)) {
                conn.commit();
            } else {
                result = false;
                conn.rollback();
            }
        } catch (SQLException e) {
            try {
                result = false;
                conn.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        } finally {
            ConnectionTool.closed(conn, ps_insert);
        }
        return result;
    }

    @Override
    public boolean update(User person) {

        PreparedStatement ps_update = null;

        try {
            conn = ConnectionTool.getDefaultConn();
            String sql = "update people set UserName=?,password=?,job=?,sal=? where userno=?";

            ps_update = conn.prepareStatement(sql);

            ps_update.setString(1, person.getUserName());
            ps_update.setString(2, person.getPassword());
            ps_update.setString(3, person.getJob());
            ps_update.setInt(4, person.getSal());
            ps_update.setInt(5, person.getUserno());
            int rows = ps_update.executeUpdate();
            if (rows > 0) {
                System.out.println("更新成功");
            } else {
                System.out.println("更新失败");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            ConnectionTool.closed(conn, ps_update);
        }

        return false;
    }


    @Override
    public boolean delete(String[] ids) {

        PreparedStatement ps_delete = null;

        try {
            conn = ConnectionTool.getDefaultConn();
            String sql = "delete from people where userno=?";

            for (int i = 0; i < ids.length; i++) {
                ps_delete = conn.prepareStatement(sql);
                ps_delete.setString(1, ids[i]);
                int rows = ps_delete.executeUpdate();
                if (rows > 0) {
                    System.out.println("删除成功");
                } else {
                    System.out.println("用户不存在");
                }
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            ConnectionTool.closed(conn, ps_delete);
        }
        return false;
    }

    @Override
    public List<User> getAll() throws SQLException {
        List<User> users = new ArrayList<>();
        String sql = "select * from tb_user";
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        try {
            while (rs.next()) {
                users.add(new User(
                        rs.getInt("userno"),
                        rs.getString("username"),
                        rs.getString("password"),
                        rs.getString("job"),
                        rs.getInt("sal")
                ));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            ConnectionTool.closed(conn,ps,rs);
        }
        return users;
    }

    public boolean login(String loginname, String userpwd) throws SQLException {
        String sql = "SELECT COUNT(*) FROM tb_user WHERE userno = ? AND password = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        try {
            ps.setString(1, loginname);
            ps.setString(2, userpwd);
            try (ResultSet rs = ps.executeQuery()) {
                return rs.next() && rs.getInt(1) > 0;
            }
        }catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            ConnectionTool.closed(conn,ps);
        }
    }

    @Override
    public List<User> getPersonForPage(int pagesize, int pageOrder) {
        return List.of();
    }

    @Override
    public User getPersonById(int id) {
        return null;
    }
}
